/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.web.controller.admin;

import cn.easyplatform.lang.Strings;
import cn.easyplatform.messages.request.SimpleRequestMessage;
import cn.easyplatform.messages.vos.SqlVo;
import cn.easyplatform.spi.service.AddonService;
import cn.easyplatform.type.IResponseMessage;
import cn.easyplatform.web.dialog.MessageBox;
import cn.easyplatform.web.service.ServiceLocator;
import org.zkoss.util.resource.Labels;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.select.SelectorComposer;
import org.zkoss.zk.ui.select.annotation.Listen;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zul.*;

import java.util.List;

/**
 * @Author: <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @Description:
 * @Since: 2.0.0 <br/>
 * @Date: Created in 2019/11/2 10:09
 * @Modified By:
 */
public class EventLogController extends SelectorComposer<Component> {

    @Wire("datebox#opTime")
    private Datebox opTime;

    @Wire("combobox#opType")
    private Combobox opType;

    @Wire("combobox#opDevice")
    private Combobox opDevice;

    @Wire("combobox#pageSize")
    private Combobox pageSize;

    @Wire("paging#paging")
    private Paging paging;

    @Wire
    private Textbox opUser;

    @Wire("grid#grid")
    private Grid grid;

    private String typeCondition;

    @Override
    public void doAfterCompose(Component comp) throws Exception {
        super.doAfterCompose(comp);
        pageSize.setSelectedIndex(0);
        String type = (String) Executions.getCurrent().getArg().get("type");
        Comboitem ci = new Comboitem("");
        ci.setValue("");
        ci.setParent(opType);
        if ("oe".equals(type)) {
            typeCondition = "type > 1";
            ci = new Comboitem(Labels.getLabel("admin.event.begin"));
            ci.setValue("begin");
            ci.setParent(opType);
            ci = new Comboitem(Labels.getLabel("admin.event.close"));
            ci.setValue("close");
            ci.setParent(opType);
            ci = new Comboitem(Labels.getLabel("admin.event.commit"));
            ci.setValue("commit");
            ci.setParent(opType);
        } else {
            typeCondition = "type = 1";
            ci = new Comboitem(Labels.getLabel("user.login"));
            ci.setValue("login");
            ci.setParent(opType);
            ci = new Comboitem(Labels.getLabel("user.signout"));
            ci.setValue("logout");
            ci.setParent(opType);
        }
        opDevice.setSelectedIndex(0);
        search(true, 1);
    }

    private void search(boolean init, int pageNo) {
        SqlVo gv = new SqlVo();
        StringBuilder sb = new StringBuilder("SELECT eventTime,userId,deviceType,event,content FROM sys_event_info WHERE ");
        sb.append(typeCondition);
        if (opDevice.getSelectedIndex() > 0) {
            sb.append(" AND deviceType = ?");
            gv.setParameter(opDevice.getSelectedItem().getValue());
        }
        if (opType.getSelectedIndex() > 0) {
            sb.append(" AND event = ?");
            gv.setParameter(opType.getSelectedItem().getValue());
        }
        if (opTime.getValue() != null) {
            sb.append(" AND eventTime >= ?");
            gv.setParameter(opTime.getValue());
        }
        if (!Strings.isBlank(opUser.getValue())) {
            sb.append(" AND userId = ?");
            gv.setParameter(opUser.getValue());
        }
        gv.setQuery(sb.toString());
        gv.setPageNo(pageNo);
        gv.setPageSize(Integer.parseInt(pageSize.getSelectedItem().getLabel()));
        gv.setGetTotalCount(init);
        AddonService as = ServiceLocator
                .lookup(AddonService.class);
        gv.setOrderBy("eventTime");
        IResponseMessage<?> resp = as.selectList(new SimpleRequestMessage(gv));
        if (resp.isSuccess()) {
            grid.getRows().getChildren().clear();
            List<Object[]> data = null;
            if (init) {
                Object[] result = (Object[]) resp.getBody();
                data = (List<Object[]>) result[1];
                paging.setTotalSize((Integer) result[0]);
            } else
                data = (List<Object[]>) resp.getBody();
            for (Object[] rec : data) {
                Row row = new Row();
                row.appendChild(new Label(rec[0].toString()));
                row.appendChild(new Label(rec[1].toString()));
                row.appendChild(new Label(Labels.getLabel("admin.event." + rec[2].toString())));
                if (opType.getItemCount() == 3)
                    row.appendChild(new Label(Labels.getLabel("user." + rec[3].toString())));
                else
                    row.appendChild(new Label(Labels.getLabel("admin.event." + rec[3].toString())));
                row.appendChild(new Label(rec[4].toString()));
                row.setParent(grid.getRows());
            }
        } else {
            MessageBox.showMessage(resp);
        }
    }

    @Listen("onClick = #search")
    public void onSearch() {
        paging.setActivePage(0);
        paging.setPageSize(Integer.parseInt(pageSize.getSelectedItem().getLabel()));
        search(true, 1);
    }

    @Listen("onClick = #clear")
    public void onClear() {
        Messagebox.show(Labels.getLabel("admin.service.op.confirm",
                new Object[]{Labels.getLabel("admin.event.clear")}), Labels.getLabel("admin.service.op.title"),
                Messagebox.CANCEL | Messagebox.OK, Messagebox.QUESTION,
                new EventListener<Event>() {
                    @Override
                    public void onEvent(Event evt) throws Exception {
                        if (evt.getName().equals(Messagebox.ON_OK)) {
                            SqlVo gv = new SqlVo();
                            StringBuilder sb = new StringBuilder("DELETE FROM sys_event_info WHERE ");
                            sb.append(typeCondition);
                            if (opType.getSelectedIndex() > 0) {
                                sb.append(" AND event = ?");
                                gv.setParameter(opType.getSelectedItem().getValue());
                            }
                            if (opTime.getValue() != null) {
                                sb.append(" AND eventTime >= ?");
                                gv.setParameter(opTime.getValue());
                            }
                            if (!Strings.isBlank(opUser.getValue())) {
                                sb.append(" AND userId = ?");
                                gv.setParameter(opUser.getValue());
                            }
                            gv.setQuery(sb.toString());
                            AddonService dbs = ServiceLocator.lookup(AddonService.class);
                            IResponseMessage<?> resp = dbs.update(new SimpleRequestMessage(gv));
                            if (resp.isSuccess()) {
                                paging.setActivePage(0);
                                grid.getRows().getChildren().clear();
                            } else
                                MessageBox.showMessage(resp);
                        }
                    }
                });

    }

    @Listen("onPaging = #paging")
    public void onPaging() {
        search(false, paging.getActivePage() + 1);
    }
}
